package com.uphone.magicleafteacher.pro.activity;

import android.arch.lifecycle.LifecycleOwner;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.radish.baselibrary.Intent.IntentData;
import com.radish.baselibrary.Intent.IntentUtils;
import com.radish.baselibrary.utils.ActivityCollector;
import com.radish.baselibrary.utils.LogUtils;
import com.radish.framelibrary.view.glide.GlideUtils;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.uphone.magicleafteacher.MyApp;
import com.uphone.magicleafteacher.R;
import com.uphone.magicleafteacher.base.BaseGActivity;
import com.uphone.magicleafteacher.http.ApiService;
import com.uphone.magicleafteacher.http.FailureConsumer;
import com.uphone.magicleafteacher.http.RequestBodyUtil;
import com.uphone.magicleafteacher.http.RxSchedulers;
import com.uphone.magicleafteacher.http.SuccessfulConsumer;
import com.uphone.magicleafteacher.pro.activity.listenertraining.ListenerTrainingActivity;
import com.uphone.magicleafteacher.pro.activity.listenertrainscore.ListenerTrainScoreActivity;
import com.uphone.magicleafteacher.util.AudioPlayProgressUtil;
import com.uphone.magicleafteacher.util.CheckButton;
import com.uphone.magicleafteacher.util.CommonUtil;
import com.uphone.magicleafteacher.util.DateUtils;
import com.uphone.magicleafteacher.util.DialogUtils;
import com.uphone.magicleafteacher.util.GsonUtils;
import com.uphone.magicleafteacher.view.RecordLoadingView1;
import com.uphone.magicleafteacher.vo.BookBorrowingDetailEvent;
import com.uphone.magicleafteacher.vo.VoiceReadBean;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class VoiceReadActivity extends BaseGActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.et_score1)
    EditText etScore1;
    @BindView(R.id.et_score2)
    EditText etScore2;
    @BindView(R.id.et_score3)
    EditText etScore3;
    @BindView(R.id.et_score4)
    EditText etScore4;
    @BindView(R.id.et_score5)
    EditText etScore5;
    @BindView(R.id.et_score6)
    TextView etScore6;
    @BindView(R.id.iv_book_face)
    ImageView ivBookFace;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.btn_submit)
    CheckButton btnSubmit;
    @BindView(R.id.recordLoadingView)
    RecordLoadingView1 recordLoadingView;
    @BindView(R.id.tv_duration)
    TextView tvDuration;
    @BindView(R.id.iv_play1)
    ImageView ivPlay1;
    @BindView(R.id.sb_audio)
    SeekBar sbAudio;
    @BindView(R.id.tv_duration1)
    TextView tvDuration1;
    @BindView(R.id.ll_readed)
    LinearLayout llReaded;
    private AudioPlayProgressUtil audioUtil;
    private AudioPlayProgressUtil audioUtil1;

    @IntentData
    private int id;
    @IntentData
    private String title = "";
    private String audioBook;
    private String audio;
    private String time;
    private File videoFile;

    @Override
    protected void initBundle() {

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_voice_read;
    }

    @Override
    protected void initView() {
        showCommit(true);
        audioUtil = new AudioPlayProgressUtil();
        audioUtil1 = new AudioPlayProgressUtil();
        TextChang textChang = new TextChang();
        etScore1.addTextChangedListener(textChang);
        etScore2.addTextChangedListener(textChang);
        etScore3.addTextChangedListener(textChang);
        etScore4.addTextChangedListener(textChang);
        etScore5.addTextChangedListener(textChang);


        btnSubmit.setRelaViews(new CheckButton.ChangeCallback() {
            @Override
            public void click(boolean enable) {
                if (enable) {
                    giveGuideMark();
                } else {
                    ToastUtils.showShort("请完善评分");
                }
            }
        }, etScore1, etScore2, etScore3, etScore4, etScore5, etScore6, etContent);
    }

    private void giveGuideMark() {
        if (videoFile == null || !videoFile.exists()) {
            ToastUtils.showShort("请录制指导音频");
            return;
        }
        Map<String, RequestBody> params = new HashMap<>();
        params.put("followWorkId", RequestBodyUtil.convertToRequestBody(id + ""));
        params.put("remark", RequestBodyUtil.convertToRequestBody(etContent.getText().toString()));
        params.put("coordinateScore", RequestBodyUtil.convertToRequestBody(etScore1.getText().toString()));
        params.put("accuracyScore", RequestBodyUtil.convertToRequestBody(etScore2.getText().toString()));
        params.put("imitationScore", RequestBodyUtil.convertToRequestBody(etScore3.getText().toString()));
        params.put("fluencyScore", RequestBodyUtil.convertToRequestBody(etScore4.getText().toString()));
        params.put("thoughtScore", RequestBodyUtil.convertToRequestBody(etScore5.getText().toString()));
        params.put("jifen", RequestBodyUtil.convertToRequestBody(etScore6.getText().toString()));
        MultipartBody.Part part = RequestBodyUtil.filesToMultipartBodyPart("file", videoFile);
        MyApp.apiService(ApiService.class)
                .giveGuideMark(params, part)
                .compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> {
                    showLoading();
                })
                .doFinally(() -> {
                    closeLoading();
                })
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) this)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String jsonObject) {
                        ToastUtils.showShort("提交成功！");
                        EventBus.getDefault().post(new BookBorrowingDetailEvent());
                        initData();
                    }
                }, new FailureConsumer());
    }

    class TextChang implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            try {
                String score1 = etScore1.getText().toString();
                String score2 = etScore2.getText().toString();
                String score3 = etScore3.getText().toString();
                String score4 = etScore4.getText().toString();
                String score5 = etScore5.getText().toString();
                int scor1 = Integer.valueOf(score1).intValue();
                int scor2 = Integer.valueOf(score2).intValue();
                int scor3 = Integer.valueOf(score3).intValue();
                int scor4 = Integer.valueOf(score4).intValue();
                int scor5 = Integer.valueOf(score5).intValue();
                int sum = scor1 + scor2 + scor3 + scor4 + scor5;
                etScore6.setText("" + sum + "");
            } catch (Exception ignored) {

            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    }

    @Override
    protected void initTitle() {
        initTitle(title + "语音跟读");
    }

    @Override
    protected void initData() {
        MyApp.apiService(ApiService.class)
                .audioRemarkDetail("" + id)
                .compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> {
                    showLoading();
                })
                .doFinally(() -> {
                    closeLoading();
                })
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) this)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String jsonObject) {
                        VoiceReadBean bean = GsonUtils.getGson().fromJson(jsonObject, VoiceReadBean.class);
                        if (bean != null && bean.getAudioWorkDetail() != null) {
                            loadData(bean.getAudioWorkDetail());
                        }
                    }
                }, new FailureConsumer());
    }

    private void loadData(VoiceReadBean.AudioWorkDetailBean bean) {
        GlideUtils.getInstance().loadNormalImage(this,
                CommonUtil.getImageUrl(bean.getFacePic()), ivBookFace);

        audioBook = CommonUtil.getVideoUrl(bean.getAudioPath());
        if (bean.getRemarkStatus() == 2) {
            //已评分
            showCommit(false);
            etScore1.setText(bean.getCoordinateScore() + "");
            etScore2.setText(bean.getAccuracyScore() + "");
            etScore3.setText(bean.getImitationSocre() + "");
            etScore4.setText(bean.getFluencyScore() + "");
            etScore5.setText(bean.getThoughtSocre() + "");
            etScore6.setText(bean.getJifen() + "");
            etContent.setText(bean.getRemark());
            setEnable(etScore1, etScore2, etScore3, etScore4, etScore5, etScore6, etContent);
            audio = CommonUtil.getVideoUrl(bean.getRemarkAudio());
            AudioPlayProgressUtil.getDurationByUrl(audio, duration -> {
                time = DateUtils.getTimeFormLong(duration);
                tvDuration1.setText(time);
            });
        } else {
            showCommit(true);
        }
    }

    private void showCommit(boolean flag) {
        if (flag) {
            llReaded.setVisibility(View.GONE);
            btnSubmit.setVisibility(View.VISIBLE);
            recordLoadingView.setVisibility(View.VISIBLE);
        } else {
            llReaded.setVisibility(View.VISIBLE);
            btnSubmit.setVisibility(View.GONE);
            recordLoadingView.setVisibility(View.GONE);
        }
    }

    private void setEnable(View... views) {
        if (views == null || views.length == 0)
            return;
        for (int i = 0; i < views.length; i++) {
            if (views[i] != null) {
                views[i].setEnabled(false);
            }
        }
    }

    @Override
    protected void initListener() {
        audioUtil1.setProgressListener(sbAudio, new AudioPlayProgressUtil.ProgressListener() {
            @Override
            public void start() {
                ivPlay1.setSelected(true);
            }

            @Override
            public void progress(int progress, int currentDuration, int totalDuration) {
                if (progress != sbAudio.getProgress())
                    sbAudio.setProgress(progress);
                tvDuration1.setText("" + DateUtils.getTimeFormLong(currentDuration));
            }

            @Override
            public void completion() {
                ivPlay1.setSelected(false);
                tvDuration1.setText(time);
            }

            @Override
            public void stop() {
                ivPlay1.setSelected(false);
            }

            @Override
            public void fail() {
                ivPlay1.setSelected(false);
            }
        });
    }


    @OnClick({R.id.iv_book_face, R.id.iv_play, R.id.iv_play1, R.id.recordLoadingView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //播放跟读
            case R.id.iv_play:
                if (!view.isSelected()) {
                    audioUtil.play(audioBook);
                } else {
                    audioUtil.stop();
                }
                break;
            //播放跟读
            case R.id.iv_play1:
                if (!view.isSelected()) {
                    audioUtil1.play(audio);
                } else {
                    audioUtil1.stop();
                }
                break;
            //录音
            case R.id.recordLoadingView:
                if (recordLoadingView.getType() != 1) {
                    // 录制
                    tvDuration.setVisibility(View.GONE);
                    recordLoadingView.setPlaying(this, 1);
                } else {
                    recordLoadingView.setPlaying(this, 2, result -> {
                        if (result.exists()) {//录音完成
                            ToastUtils.showShort("录音完成");
                            videoFile = result;
                            AudioPlayProgressUtil.getDurationByUrl(videoFile.getAbsolutePath(), duration -> {
                                tvDuration.setText(DateUtils.getTimeFormLong(duration) + "");
                                tvDuration.setVisibility(View.VISIBLE);
                                DialogUtils.saveAudioDialogNoCommit(VoiceReadActivity.this, videoFile.getAbsolutePath(), (dialog, view1, type) -> {
                                    switch (type) {
                                        case 1:// 录音试听
                                            break;
                                        case 2:// 再来一次
                                            recordLoadingView.setPlaying(this, 1);
                                            tvDuration.setVisibility(View.GONE);
                                            break;
                                    }
                                });
                            });
                        } else {
                            ToastUtils.showShort("录音失败");
                            videoFile = null;
                            recordLoadingView.setPlaying(this, 0);
                        }
                    });
                }
                break;
        }
    }
}
